package accs.model.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.util.StringTokenizer;

import accs.model.UserPasswordPair;

public class LineUserPasswordReader extends UserPasswordReader {

	private BufferedReader reader;
	private String delim="|";
	private int userColumn=0;
	private int passColumn=1;
	
	public LineUserPasswordReader(Reader reader) {
		this.reader = new BufferedReader(reader);
	}

	public LineUserPasswordReader(Reader reader, String delim, int userColumn, int passColumn) {
		this.reader = new BufferedReader(reader);
		this.delim = delim;
		this.userColumn = userColumn;
		this.passColumn = passColumn;
	}
	
	public UserPasswordPair read() throws IOException {
		String line=null;
		
		while((line=reader.readLine())!=null && line.trim().isEmpty()) {}
		if(line==null) return null;
		
		StringTokenizer tk=new StringTokenizer(line,delim);
		int columnCounter=0;
		
		String user=null, pass=null;
		
		while(tk.hasMoreTokens()) {
			String token=tk.nextToken(); //System.out.println("TOKEN: "+token);
			
			if(columnCounter==userColumn) user=token;
			else if(columnCounter==passColumn) pass=token;
			
			columnCounter++;
		}
		
		if(user==null || pass==null) {
			System.out.println("Error: "+line);
		} 
		
		return new UserPasswordPair(user==null ? "" : user, pass==null ? "" : pass);
	}

	public void close() throws IOException {
		reader.close();
	}
}